<template>
  <div @contextmenu.prevent.stop="contextMenuHandler">
    <slot />
    <transition name="fade">
      <div
        v-show="openMenu"
        class="right-click-wrapper"
        @click.stop.self="blurHandler"
        @contextmenu.prevent.stop="blurHandler"
      >
        <ul :style="{top: top, left: left }" class="v-right-click-menu">
          <li v-for="item in items" :key="item.id" @click.prevent="handleClick(item)">
            <div v-if="item.template" v-html="item.template" />
            <span v-else>{{ item.name }}</span>
          </li>
        </ul>
      </div>
    </transition>
  </div>
</template>

<script>
export default {
  props: {
    items: {
      type: Array,
      default() {
        return null;
      }
    }
  },
  data() {
    return {
      openMenu: false,
      top: 0,
      left: 0,
      handleEvent: null
    };
  },
  mounted() {
    this.handleEvent = function() {
      this.openMenu = false;
    };
    window.document.querySelector("html").addEventListener("contextmenu", this);
  },
  beforeDestroy() {
    window.document
      .querySelector("html")
      .removeEventListener("contextmenu", this);
  },
  methods: {
    contextMenuHandler(e) {
      this.top = `${e.clientY +
        document.body.scrollTop +
        document.documentElement.scrollTop}px`;
      this.left = `${e.clientX +
        document.body.scrollLeft +
        document.documentElement.scrollLeft}px`;
      this.openMenu = true;
    },
    blurHandler() {
      this.openMenu = false;
    },
    handleClick(item) {
      this.$emit("action", item);
      this.openMenu = false;
    }
  }
};
</script>

<style lang="scss">
.right-click-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
}
.v-right-click-menu {
  position: fixed;
  z-index: 1000;
  border-radius: 4px;
  background:#f0f0f0;
  color: #333;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin: 0;
  padding: 0;
  overflow: hidden;
  cursor: pointer;
  li {
    list-style-type: none;
    padding: 5px 10px;
    & > div {
      display: flex;
      align-items: center;
      img {
        display: inline-block;
        margin-right: 8px;
      }
    }
    &:hover {
      color: #000;
      background-color: #fff;
    }
  }
  li:not(:last-child) {
    border-bottom: 1px solid #666;
  }
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
}
</style>
